<!DOCTYPE html>
<html>
<head>
    <title>折线图</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <canvas id="lineChart" width="400" height="300"></canvas>

    <script>
        // 获取 canvas 元素
        var canvas = document.getElementById('lineChart');
        var ctx = canvas.getContext('2d');

        // 定义数据
        var data = [30, 50, 80, 120, 200]; // 折线图的数据

        // 设置绘图参数
        var lineWidth = 2; // 折线宽度
        var pointRadius = 4; // 折线数据点半径
        var maxValue = Math.max(...data); // 数据中的最大值
        var chartHeight = canvas.height - 40; // 图表的高度，减去一些空白边距
        var chartWidth = canvas.width - 60; // 图表的宽度，减去一些空白边距

        // 绘制坐标轴
        ctx.beginPath();
        ctx.moveTo(40, canvas.height - 20);
        ctx.lineTo(40, 20);
        ctx.lineTo(canvas.width - 20, 20);
        ctx.lineWidth = 1;
        ctx.strokeStyle = '#000';
        ctx.stroke();

        // 绘制 x 轴刻度
        ctx.textAlign = 'center';
        ctx.fillStyle = '#000';
        for (var i = 0; i < data.length; i++) {
            var x = 40 + (i * (chartWidth / (data.length - 1)));
            ctx.fillText(i, x, canvas.height - 5);
        }

        // 绘制 y 轴刻度
        ctx.textAlign = 'right';
        ctx.textBaseline = 'middle';
        var yStep = maxValue / 5;
        for (var j = 0; j <= 5; j++) {
            var y = (canvas.height - 20) - (j * (chartHeight / 5));
            ctx.fillText(yStep * j, 35, y);
        }

        // 绘制折线图
        ctx.beginPath();
        ctx.lineWidth = lineWidth;
        ctx.strokeStyle = '#336699';
        ctx.moveTo(40, canvas.height - 20 - ((data[0] / maxValue) * chartHeight));

        for (var k = 1; k < data.length; k++) {
            var x = 40 + (k * (chartWidth / (data.length - 1)));
            var y = canvas.height - 20 - ((data[k] / maxValue) * chartHeight);

            // 绘制折线
            ctx.lineTo(x, y);
            ctx.stroke();

            // 绘制数据点
            ctx.beginPath();
            ctx.arc(x, y, pointRadius, 0, Math.PI * 2);
            ctx.fillStyle = '#336699';
            ctx.fill();
            ctx.closePath();

            // 连接数据点
            ctx.moveTo(x, y);
        }
    </script>
</body>
</html>
